package com.java_project.src.network;

import com.java_project.src.Product;
import com.java_project.src.ProductService;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;

public class EStoreServer {
    private final ProductService productService = new ProductService();
    private static final int PORT = 8888;

    public static void main(String[] args) {
        new EStoreServer().start();
    }

    private void start() {
        try (ServerSocket serverSocket = new ServerSocket(PORT)) {
            System.out.println("服务器启动，监听端口：" + PORT);
            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("客户端已连接");
                handleClient(clientSocket);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void handleClient(Socket clientSocket) {
        try (ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream());
             ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream())) {
            String request = (String) ois.readObject();
            if ("GET_ALL_PRODUCTS".equals(request)) {
                List<Product> products = productService.getAllProducts();
                oos.writeObject(products);
                oos.flush();
                System.out.println("已向客户端返回商品列表");
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}